﻿using System.Reflection;
using CapHttp.Core.Extensions;
using DotNetCore.CAP;

namespace CapHttp.Core;

public class CapEventPublisher : IDistributedEventPublisher
{
    private readonly ICapPublisher _cap;

    public CapEventPublisher(ICapPublisher cap)
    {
        _cap = cap;
    }

    public ICapPublisher CapPublisher => _cap;

    public async Task PublishAsync<T>(string name, T eventData)
    {
        var headers = BuildHeader<T>();
        await _cap.PublishAsync(name, eventData, headers);
    }

    public async Task PublishAsync<T>(T eventData)
    {
        var eventName = typeof(T).GetEventName();
        
        var headers = BuildHeader<T>();
        await _cap.PublishAsync(eventName, eventData, headers);
    }

    public void Publish<T>(string name, T eventData)
    {
        var headers = BuildHeader<T>();
        _cap.Publish(name, eventData, headers);
    }

    public void Publish<T>(T eventData)
    {
        var eventName = typeof(T).GetEventName();
        
        var headers = BuildHeader<T>();
        _cap.Publish(eventName, eventData, headers);
    }

    private static IDictionary<string, string> BuildHeader<T>()
    {
        var type = typeof(T);
        var attribute = type.GetCustomAttribute<EventAttribute>();
        var apiName = attribute?.ApiName;
        
        IDictionary<string, string> headers = new Dictionary<string, string>();
        if (!string.IsNullOrEmpty(apiName))
            headers.Add(CapHttpConstants.API_NAME_HEADER, apiName);
        
        return headers;
    }
}